package com.kfd.demo.service.Impl;

import com.google.gson.Gson;
import com.kfd.demo.dao.UserDao;
import com.kfd.demo.entity.user.Order_Tb;
import com.kfd.demo.entity.user.User;
import com.kfd.demo.service.UserServe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServeImpl implements UserServe {
    @Autowired
    UserDao userDao;

    @Override
    public List login(User theUser) {
        User newUser = null;
//        用户登录，先匹配账号，入宫账号不存在则新建一个新用户
        theUser.setU_id(0);
        List isUser = userDao.selectUser(theUser.getU_acc());
        if (isUser.size() == 0) {
//            如果用户表中不存在该用户，那么直接新建账号给用户
            newUser = new User(
                    0,
                    theUser.getU_acc().toString(),
                    theUser.getU_name().toString(),
                    theUser.getU_phone_number().toString()
//                    theUser.getU_note().toString()
            );
//            然后创建新的用户
            userDao.addUser(newUser);
            //创建后再匹配一次
            return null;
        }
        return isUser;
    }

    //        获取用户订单
    @Override
    public Map<Integer, List<Order_Tb>> getUserOrder(int uid, int GroupId) {
        System.out.println(uid + "这是我拿用户的订单的" + GroupId);
// 这里做一个判断，如果是查所有订单，就创建一个数组
        List<Order_Tb> TheUserOrderList = userDao.getUserOrder(uid, GroupId);

        ArrayList<Integer> orderGroup = new ArrayList<>();
        for (Order_Tb theOrderItem : TheUserOrderList) {
//            System.out.println(theOrderItem);
            if (!orderGroup.contains(theOrderItem.getOrder_groupID())) {
                orderGroup.add(theOrderItem.getOrder_groupID());
            }
        }

        Map<Integer, List<Order_Tb>> orderMap = new HashMap<>();
        for (Integer gid : orderGroup) {
            List<Order_Tb> ordersWithSameGroup = TheUserOrderList.stream()
                    .filter(order -> order.getOrder_groupID() == gid)
                    .collect(Collectors.toList());
            orderMap.put(gid, ordersWithSameGroup);
        }

// 打印归类结果
        orderMap.forEach((gid, orders) -> {
//            System.out.println("Order_groupID: " + gid);
            orders.forEach(order -> System.out.println("\t" + order));
        });

        System.out.println(orderGroup.toString());
        Gson gson = new Gson();
        return orderMap;
//        return userDao.getUserOrder(uid, GroupId);
    }

    @Override
    public int UserPurchase(
            int uid,
            int GoodsId,
            int group,
            int number,
            String cartNote) {
// 如果是真实使用的话会传入一个价格来验证，避免价格出错，此处就不做了

//        int success = 0;
        return userDao.UserPurchase(uid, GoodsId, group, number, cartNote);
    }
}
